<?php
namespace Mobile\Controller;

class NewsPushController extends ParentController {
    protected function _initialize() {
        $this->validateUtil = new \Org\Util\Validate();
        if (!in_array(ACTION_NAME, array('getNewsList', 'newSaveNews', 'getRoomCheck', 'deleteRoomCheck'))) {
            parent::_initialize();
            $param = I('post.');
            $validateRule = array(
                'userId' => 'notnull,notempty,id',
                'hotel' => 'notnull,notempty,id',
            );
            $this->ajaxValidateReturn($this->validateUtil, $param, $validateRule);

            $hotelId = $param['hotel'];
            $userId = $param['userId'];
        }

        //检查操作权限
        $adminAuthorityLogic = A('Common/AdminAuthority', 'Logic');
        if (!in_array(ACTION_NAME, array('pushManage', 'getHotelNewsCount', 'getNewsList', 'newSaveNews', 'getRoomCheck', 'getRoomCheckDetail', 'editRoomCheck', 'deleteRoomCheck', 'getCheckResource'))) {
            $adminAuthorityLogic->check($hotelId, $userId);
        }
    }
	/**
     * 消息推送控制器
     * @modify wenhui 2017-03-16     创建
     * @modify zhangzhen 2017-06-05  钟点房版本控制
     */
	public function getNewsList() {
		$param = I('post.');

		$validateRule = array(
            'hotel' => 'notnull,notempty',
            'userId' => 'notnull,notempty,id',
            'token' => 'notnull,notempty',
        );

        $version = getVersion(array('2.0.15'));
        if ($version >= '2.0.15') {
            $validateRule['currentPage'] = 'notnull,notempty';
            $validateRule['pageSize'] = 'notnull,notempty';
        }

        $validatePass = $this->ajaxValidateReturn($this->validateUtil, $param, $validateRule);
        if (!$validatePass) {
            return;
        }

        $newsPushLogic = A('Common/NewsPush', 'Logic');
        $hotelId = json_decode(stripcslashes(htmlspecialchars_decode($param['hotel'])), true);
        $userId = $param['userId'];
        $token = $param['token'];
        $currentPage = isset($param['currentPage']) ? $param['currentPage'] : null;
        $pageSize = isset($param['pageSize']) ? $param['pageSize'] : null;
        $keys = isset($param['keys']) ? $param['keys'] : null;
        $type = isset($param['type']) ? $param['type'] : null;

        //检查token
        $this->checkMobileToken($userId, $token);
        // 获取数据
        $newsPushInfo = $newsPushLogic->getNewsList($hotelId, $userId, $currentPage, $pageSize, $keys, $type);

        $version = getCurrentVersion();
        $hourVersion = C('MOBILE_VERSION')['hour_room'];
        if (isset($newsPushInfo['newsList']) && !empty($newsPushInfo['newsList'])) {
            if ($version < $hourVersion) {
                foreach ($newsPushInfo['newsList'] as $key => &$info) {
                    if ($info['hour'] > 0) {
                        unset($newsPushInfo['newsList'][$key]);
                    }
                    $info['startTime'] = substr($info['startTime'],0,10);
                }
                unset($info);
                $newsPushInfo['newsList'] = array_values($newsPushInfo['newsList']);
            }
            $longVersion = C('MOBILE_VERSION')['long_room'];
            if ($version < $longVersion) {
                foreach ($newsPushInfo['newsList'] as $key => &$info) {
                    if ($info['month'] > 0) {
                        unset($newsPushInfo['newsList'][$key]);
                    }
                }
                unset($info);
                $newsPushInfo['newsList'] = array_values($newsPushInfo['newsList']);
            }
        } else {
            if (isset($newsPushInfo['page'])) {
                returnJson(403, 800, 'error');
                return;
            }
            if ($version < $hourVersion) {
                foreach ($newsPushInfo as $key => &$info) {
                    if ($info['hour'] > 0) {
                        unset($newsPushInfo[$key]);
                    }
                    $info['startTime'] = substr($info['startTime'],0,10);
                }
                unset($info);
                $newsPushInfo = array_values($newsPushInfo);
            }
            $longVersion = C('MOBILE_VERSION')['long_room'];
            if ($version < $longVersion) {
                foreach ($newsPushInfo as $key => &$info) {
                    if ($info['month'] > 0) {
                        unset($newsPushInfo[$key]);
                    }
                }
                unset($info);
                $newsPushInfo = array_values($newsPushInfo);
            }
        }

        if (empty($newsPushInfo)) {
            returnJson(403, 800, 'error');
        }

    	returnJson(200, 200, $newsPushInfo);
	}

    /**
     * 消息推送编辑
     * @modify wenhui 2017-03-16    创建
     */
    public function saveNews() {

        $param = I('post.');
        $validateRule = array(
            'userId' => 'notnull,notempty,id',
            'token' => 'notnull,notempty',
            'hotel' => 'notnull,notempty,id',
            'newsList' => 'notnull',
            'allOperate' => 'notnull,notempty',
        );
        $validatePass = $this->ajaxValidateReturn($this->validateUtil, $param, $validateRule);
        if (!$validatePass) {
            return;
        }

        if ($param['allOperate'] == 1 || $param['allOperate'] == 2) {
            $newsList = json_decode(stripslashes(htmlspecialchars_decode($param['newsList'])), true);
            $validateRule = array(
                'newsPushId' => 'notnull,notempty,id',
                'newsPushRelateId' => 'notnull,notempty,id',
                'type' => 'notnull,notempty',
            );
            foreach ($newsList as $key => $newsListItem) {
                $validatePass = $this->ajaxValidateReturn($this->validateUtil, $newsListItem, $validateRule);
                if (!$validatePass) {
                    return;
                }
            }
            unset($newsListItem);
        }

        $userId = $param['userId'];
        $token = $param['token'];
        $hotel = $param['hotel'];
        $allOperate = $param['allOperate'];
        $channel = 1;
        if (empty($param['newsList'])) {
            $newsList = $param['newsList'];
        }

        $newsPushLogic = A('Common/NewsPush', 'Logic');
        //检查token
        $this->checkMobileToken($userId, $token);
 
        if ($allOperate == 3 || $allOperate == 4) {
            // 全部操作
            $saveInfo = array(array('newsPushRelateId' =>'', 'type' => $allOperate, 'newsPushId' => ''));
            $newsPushInfo = $newsPushLogic->saveNews($saveInfo, $userId, $channel);
        } else {
            $hotelNewsPushRelateModel = D('HotelNewspushRelate');
            // 已读 和 删除 获取不同的数据做比较 筛选
            $type = $allOperate == 1 ? 0 : null;
            $newsPushInfo = $hotelNewsPushRelateModel->getNewsRelateByHotelAndUserId($hotel, $userId, $type);

            // 过滤不可以修改或删除的信息
            $newsPushInfo = getArrayValueAsIndex($newsPushInfo, 'id');
            foreach ($newsList as $key => $newsListItem) {
                if (!isset($newsPushInfo[$newsListItem['newsPushRelateId']])) {
                    unset($newsList[$key]);
                }
            }
            unset($newsListItem);

            if (empty($newsList)) {
                returnJson(403, 802);
            }

            // 只根据 newsPushRelateId 修改
            $newsPushInfo = $newsPushLogic->saveNews($newsList, $userId, $channel);
        }
  
        if ($newsPushInfo) {
            returnJson(200, 200, array());
        }     
    }

    /**
     * 消息推送编辑
     * @modify wenhui 2017-03-16    创建
     */
    public function newSaveNews() {

        $param = I('post.');
        $validateRule = array(
            'userId' => 'notnull,notempty,id',
            'token' => 'notnull,notempty',
            'newsList' => 'notnull,notempty',
        );
        $validatePass = $this->ajaxValidateReturn($this->validateUtil, $param, $validateRule);
        if (!$validatePass) {
            return;
        }

        $newsList = json_decode(stripslashes(htmlspecialchars_decode($param['newsList'])), true);
        $validateRule = array(
            'newsPushId' => 'notnull,notempty,id',
            'newsPushRelateId' => 'notnull,notempty,id',
            'type' => 'notnull,notempty',
        );
        foreach ($newsList as $key => $newsListItem) {
            $validatePass = $this->ajaxValidateReturn($this->validateUtil, $newsListItem, $validateRule);
            if (!$validatePass) {
                return;
            }
        }
        unset($newsListItem);

        $userId = $param['userId'];
        $token = $param['token'];

        //检查token
        $this->checkMobileToken($userId, $token);

        $hotelNewsPushRelateModel = D('HotelNewspushRelate');
        $newsPushInfo = $hotelNewsPushRelateModel->getNewsRelateByHotelAndUserId($hotel, $userId);

        // 过滤不可以修改或删除的信息
        $newsPushInfo = getArrayValueAsIndex($newsPushInfo, 'id');
        foreach ($newsList as $key => $newsListItem) {
            if (!isset($newsPushInfo[$newsListItem['newsPushRelateId']])) {
                unset($newsList[$key]);
            }
        }
        unset($newsListItem);

        if (empty($newsList)) {
            returnJson(403, 802);
        }

        $newsPushLogic = A('Common/NewsPush', 'Logic');
        $newsPushInfo = $newsPushLogic->saveNews($newsList, $userId, 1);
        if ($newsPushInfo) {
            returnJson(200, 200, array());
        }
    }

    /**
     * 获取未读信息数量
     * @modify wenhui 2017-03-16    创建
     */
    public function getHotelNewsCount() {

        $param = I('post.');
        $validateRule = array(
            'hotel' => 'notnull,notempty,id',
            'userId' => 'notnull,notempty,id',
            'token' => 'notnull,notempty',
        );
        $validatePass = $this->ajaxValidateReturn($this->validateUtil, $param, $validateRule);
        if (!$validatePass) {
            return;
        }

        $newsPushLogic = A('Common/NewsPush', 'Logic');
        //$hotelId = $param['hotel'];
        $userId = $param['userId'];
        $token = $param['token'];

        $adminHotelModel = D('AdminHotel');
        $adminHotelInfo = $adminHotelModel->getInfoByUserLeftHotelEntity($userId);
        $hotelIds = array_column($adminHotelInfo, 'hotelentity_id');

        //检查token
        $this->checkMobileToken($userId, $token);
        // 获取数据
        $hotelNewsPushRelateModel = D('HotelNewspushRelate');
        $hotelAlarmClockModel = D('HotelAlarmClock');
        $hotelRoomCheckModel = D('HotelRoomCheck');
        $adminAuthorityModel = D('AdminAuthority');
        $hotelRoomAuthorityModel = D('HotelRoomAuthority');
        $orderRoomModel = D('OrderRoom');

        $pushRelateInfo = $hotelNewsPushRelateModel->getNewsRelateByHotelAndUserId($hotelIds, $userId, 0);
        $hotelAlarmClockInfo = $hotelAlarmClockModel->getRemindListByHotel($hotelIds, 1, 0);
        $hotelRoomCheckInfo = $hotelRoomCheckModel->getInfoByhotelId($hotelIds, 0);

        $countNews = empty(count($pushRelateInfo)) ? 0 : count($pushRelateInfo);
        $remindCountNews = empty(count($hotelAlarmClockInfo)) ? 0 : count($hotelAlarmClockInfo);

        // 获取子订单数据
        $usbOrderId = array_column($hotelRoomCheckInfo, 'orderroom_id');
        $orderRoomInfo = $orderRoomModel->getInfo($usbOrderId);
        $orderRoomInfo = getArrayValueAsIndex($orderRoomInfo, 'id');
        $roomIds = array_column($orderRoomInfo, 'roominfo_id');

        // 校验有查房权限 与 房间权限
        $authorityResult = array();
        $hotelRoomAuthorityInfo = array();
        $authorityResult = $adminAuthorityModel->getInfoByAdminHotelAuthority($userId, $hotelIds, 27);
        $authorityResult = getArrayValueAsIndex($authorityResult, 'hotelentity_id');
        $hotelRoomAuthorityInfo = $hotelRoomAuthorityModel->getInfoByUserRoom($userId, $roomIds, $hotelIds);
        $hotelRoomAuthorityInfo = getArrayValueAsIndex($hotelRoomAuthorityInfo, 'adminlogin_id', true);

        $adminHotelInfo = getArrayValueAsIndex($adminHotelInfo, 'hotelentity_id');
        foreach ($hotelRoomCheckInfo as $key => $roomCheck) {
            //检查是否为客栈管理员
            if ($adminHotelInfo[$roomCheck['hotelentity_id']] && $adminHotelInfo[$roomCheck['hotelentity_id']]['role'] != HOTEL_ROLE_OWNER) {
                // 校验有查房权限
                if (!empty($authorityResult)) {
                    if (!isset($authorityResult[$roomCheck['hotelentity_id']])) {
                        unset($hotelRoomCheckInfo[$key]);
                        continue;
                    }
                } else {
                    unset($hotelRoomCheckInfo[$key]);
                    continue;
                }

                // 过滤没有房间权限
                $orderRoom = $orderRoomInfo[$roomCheck['orderroom_id']];
                if (!empty($hotelRoomAuthorityInfo)) {
                    $adminRoomAuthorityInfo = $hotelRoomAuthorityInfo[$userId];
                    $adminRoomAuthorityInfo = getArrayValueAsIndex($adminRoomAuthorityInfo, 'roominfo_id');
                    if (!isset($adminRoomAuthorityInfo[$orderRoom['roominfo_id']])) {
                        unset($hotelRoomCheckInfo[$key]);
                        continue;
                    }
                } else {
                    unset($hotelRoomCheckInfo[$key]);
                    continue;
                }
            }
        }

        $checkCount = empty(count($hotelRoomCheckInfo)) ? 0 : count($hotelRoomCheckInfo);

        $returnData = array(
            'newsCount' => $countNews,
            'remindCountNews' => $remindCountNews,
            'checkCount' => $checkCount,
        );

        returnJson(200, 200, $returnData);
    }


    /**
     * 掌柜说推送
     * @modify wenhui 2017-03-24 创建
     */
    public function pushManage() {
        $param = I('post.');
        $validateRule = array(
            'userId' => 'notnull,notempty,id',
            'token' => 'notnull,notempty',
            'hotel' => 'notnull,notempty,id',
            'specialId' => 'notnull,notempty',
        );

        $version = getVersion(array('2.0.10'));
        if ($version >= '2.0.10') {
            $validateRule = array_merge($validateRule, ['indexs' => 'notnull,notempty']);
            $validateRuleItem = array(
                'specialId' => 'notnull,notempty,id',
                'index' => 'notnull,notempty',
            );
            $indexs = json_decode(stripslashes(htmlspecialchars_decode(html_entity_decode($param['indexs']))), true);
            foreach ($indexs as $key => $sortIndexs) {
                $this->ajaxValidateReturn($this->validateUtil, $sortIndexs, $validateRuleItem);
            }
            unset($sortIndexs);
        }
        $validatePass = $this->ajaxValidateReturn($this->validateUtil, $param, $validateRule);
        if (!$validatePass) {
            return;
        }

        $userId = $param['userId'];
        $token = $param['token'];
        $hotelId = $param['hotel'];
        $indexs = isset($indexs) ? $indexs : null;
        $specialId = json_decode(stripslashes(htmlspecialchars_decode($param['specialId'])));
        //检验token
        $this->checkMobileToken($userId, $token);
        $hotelBookLogic = A('Common/HotelBook', 'Logic');
        // 校验是否已经通过
        $isEnable = $hotelBookLogic->checkEnable($hotelId);
        if (!$isEnable) {
            returnJson(403,409);
        }

        // 推送
        $pushResult = $hotelBookLogic->pushManage($hotelId, $specialId, $indexs);

        if ($pushResult == false) {
            returnJson(403, 704);
        }

        returnJson(200, 200);
    }

    /**
     * 获取查房消息
     * @modify wenhui 2018-02-127     创建
     */
    public function getRoomCheck() {
        $param = I('post.');

        $validateRule = array(
            'hotel' => 'notnull,notempty',
            'userId' => 'notnull,notempty,id',
            'token' => 'notnull,notempty',
            'currentPage' => 'notnull,notempty,id',
            'pageSize' => 'notnull,notempty,id',
        );

        $validatePass = $this->ajaxValidateReturn($this->validateUtil, $param, $validateRule);
        if (!$validatePass) {
            return;
        }

        $hotelId = json_decode(stripcslashes(htmlspecialchars_decode($param['hotel'])), true);
        $userId = $param['userId'];
        $token = $param['token'];
        $currentPage = $param['currentPage'];
        $pageSize = $param['pageSize'];
        $keys = isset($param['keys']) ? $param['keys'] : null;

        //检查token
        $this->checkMobileToken($userId, $token);
        // 获取数据
        $newsPushLogic = A('Common/NewsPush', 'Logic');
        $roomCheckInfo = $newsPushLogic->getCheckInfo($hotelId, $keys, $currentPage, $pageSize, null, null, true);

        // 处理数据
        foreach ($roomCheckInfo['roomCheck'] as $key => &$roomCheck) {
            unset($roomCheck['name']);
            unset($roomCheck['endTime']);
            unset($roomCheck['hotelName']);
            unset($roomCheck['typeName']);
            unset($roomCheck['orderInfoId']);
            unset($roomCheck['orderRoomId']);
            unset($roomCheck['roomId']);
            unset($roomCheck['createStamp']);
            unset($roomCheck['checkCost']);
        }

        returnJson(200, 200, $roomCheckInfo);
    }

    /**
     * 获取查房消息详情
     * @modify wenhui 2018-02-127     创建
     */
    public function getRoomCheckDetail() {
        $param = I('post.');

        $validateRule = array(
            'hotel' => 'notnull,notempty,id',
            'userId' => 'notnull,notempty,id',
            'token' => 'notnull,notempty',
            'checkId' => 'notnull,notempty,id',
        );

        $validatePass = $this->ajaxValidateReturn($this->validateUtil, $param, $validateRule);
        if (!$validatePass) {
            return;
        }

        $hotelId = $param['hotel'];
        $userId = $param['userId'];
        $token = $param['token'];
        $checkId = $param['checkId'];

        //检查操作权限
        $adminAuthorityLogic = A('Common/AdminAuthority', 'Logic');
        $authorityResult = $adminAuthorityLogic->check($hotelId, $userId, 27);
        if ($authorityResult == false) {
            returnJson(403, 202);
            return;
        }
       
        //检查token
        $this->checkMobileToken($userId, $token);
        // 获取数据
        $newsPushLogic = A('Common/NewsPush', 'Logic');
        try {
            $roomCheckDetail = $newsPushLogic->getCheckDetail($hotelId, $checkId);
        } catch (\Exception $e) {
            returnJson($e->getMessage());
            return;
        }

        returnJson(200, 200, $roomCheckDetail);
    }

    /**
     * 编辑查房消息
     * @modify wenhui 2018-02-127     创建
     */
    public function editRoomCheck() {
        $param = I('post.');

        $validateRule = array(
            'hotel' => 'notnull,notempty',
            'userId' => 'notnull,notempty,id',
            'token' => 'notnull,notempty',
            'checkId' => 'notnull,notempty,id',
        );

        if (isset($param['roomCostId'])) {
            $validateRule['roomCostId'] = 'notnull,notempty';
        }
        if (isset($param['remark']) && !empty($param['remark'])) {
            $validateRule['remark'] = 'notnull,notempty,nameLength100';
        }

        $validatePass = $this->ajaxValidateReturn($this->validateUtil, $param, $validateRule);
        if (!$validatePass) {
            return;
        }

        $hotelId = $param['hotel'];
        $userId = $param['userId'];
        $token = $param['token'];
        $checkId = $param['checkId'];
        $remark = isset($param['remark']) ? $param['remark'] : null;
        $roomCostId = isset($param['roomCostId']) ? json_decode(stripcslashes(htmlspecialchars_decode($param['roomCostId'])), true) : null;

        //检查操作权限
        $adminAuthorityLogic = A('Common/AdminAuthority', 'Logic');
        $authorityResult = $adminAuthorityLogic->check($hotelId, $userId, 27);
        if ($authorityResult == false) {
            returnJson(403, 202);
            return;
        }

        //检查token
        $this->checkMobileToken($userId, $token);
        // 获取数据
        $newsPushLogic = A('Common/NewsPush', 'Logic');
        try {
            $saveResult = $newsPushLogic->editCheck($hotelId, $checkId, $roomCostId, $remark);
        } catch (\Exception $e) {
            returnJson($e->getMessage());
            return;
        }

        returnJson(200, 200);
    }

    /**
     * 删除查房消息
     * @modify wenhui 2018-02-127     创建
     */
    public function deleteRoomCheck() {
        $param = I('post.');

        $validateRule = array(
            'hotel' => 'notnull,notempty',
            'userId' => 'notnull,notempty,id',
            'token' => 'notnull,notempty',
            'checkId' => 'notnull,notempty',
        );

        $validatePass = $this->ajaxValidateReturn($this->validateUtil, $param, $validateRule);
        if (!$validatePass) {
            return;
        }

        $userId = $param['userId'];
        $token = $param['token'];
        $checkId = json_decode(stripcslashes(htmlspecialchars_decode($param['checkId'])), true);
        $hotelId = json_decode(stripcslashes(htmlspecialchars_decode($param['hotel'])), true);

        //检查操作权限
        if (!empty($hotelId)) {
            $adminAuthorityLogic = A('Common/AdminAuthority', 'Logic');
            foreach ($hotelId as $key => $hotel) {
                $authorityResult = $adminAuthorityLogic->check($hotel, $userId, 27);
                if ($authorityResult == false) {
                    returnJson(403, 202);
                    return;
                }
            }
        }

        //检查token
        $this->checkMobileToken($userId, $token);
        // 获取数据
        $newsPushLogic = A('Common/NewsPush', 'Logic');
        try {
            $deleteResult = $newsPushLogic->deleteCheck($checkId);
        } catch (\Exception $e) {
            returnJson($e->getMessage());
            return;
        }

        returnJson(200, 200);
    }

    /**
     * @description 获取查房消费物品资源
     * @modify wenhui 2018-03-01
     */
    public function getCheckResource() {
        $params = I('post.');
        $validateRule = array(
            'userId' => 'notnull,notempty,id',
            'token' => 'notnull,notempty',
            'hotel' => 'notnull,notempty,id',
        );
        $this->ajaxValidateReturn($this->validateUtil, $params, $validateRule);
        $userId = $params['userId'];
        $token = $params['token'];
        $hotelId = $params['hotel'];

        //检验token
        $this->checkMobileToken($userId, $token);
        // 渠道和支付方式
        $hotelLogic = A('Common/Hotel', 'Logic');
        $hotelRoomCostData = $hotelLogic->getCheckRoomCost($hotelId);
        $data['checkCost'] = $hotelRoomCostData;

        $data['checkCost'] = array();
        foreach ($hotelRoomCostData as $hotelRoomCost) {
            $data['checkCost'][] = array(
                'checkCostId' => $hotelRoomCost['id'],
                'name' => $hotelRoomCost['name']
            );
        }

        returnJson(200, 200, $data);
    }
}